package org.dromara.system.controller;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.lang3.tuple.Pair;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.dromara.system.domain.EmailList;
import org.dromara.system.domain.EmailTemplate;
import org.dromara.system.domain.PayOrder;
import org.dromara.system.domain.vo.EmailTemplateVo;
import org.dromara.system.kernel.SendEmail2Kernel;
import org.dromara.system.kernel.SendEmailKernel;
import org.dromara.system.mapper.EmailListMapper;
import org.dromara.system.mapper.EmailTemplateMapper;
import org.dromara.system.service.IEmailTemplateService;
import org.dromara.system.service.IPayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.EmailListVo;
import org.dromara.system.domain.bo.EmailListBo;
import org.dromara.system.service.IEmailListService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 邮件记录
 * 前端访问路由地址为:/system/EmailList
 *
 * @author Gavino
 * @date 2024-11-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/EmailList")
public class EmailListController extends BaseController {

    private final IEmailListService emailListService;
    private final IPayOrderService payOrderService;
    private final EmailTemplateMapper emailTemplateMapper;
    private final EmailListMapper emailListMapper;
    private final SendEmail2Kernel sendEmail2Kernel;

    /**
     * 查询邮件记录列表
     */
    @SaCheckPermission("system:EmailList:list")
    @GetMapping("/list")
    public TableDataInfo<EmailListVo> list(EmailListBo bo, PageQuery pageQuery) {
        return emailListService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出邮件记录列表
     */
    @SaCheckPermission("system:EmailList:export")
    @Log(title = "邮件记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(EmailListBo bo, HttpServletResponse response) {
        List<EmailListVo> list = emailListService.queryList(bo);
        ExcelUtil.exportExcel(list, "邮件记录", EmailListVo.class, response);
    }

    /**
     * 获取邮件记录详细信息
     *
     * @param emailId 主键
     */
    @SaCheckPermission("system:EmailList:query")
    @GetMapping("/{emailId}")
    public R<?> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long emailId) {
        EmailList email = emailListService.selectById(emailId);
        if (email == null) {
            return R.fail("未获取到邮件信息");
        }

        JSONObject json = JSONObject.from(email, JSONWriter.Feature.WriteMapNullValue);
        PayOrder order = payOrderService.selectById(email.getOrderId());
        if (order == null) {
            return R.fail("未获取到邮件对应的订单信息");
        }
        EmailTemplate template = emailTemplateMapper.selectById(email.getTemplateId());
        if (template == null) {
            return R.fail("未获取到邮件对应的模板");
        }
        Pair<String, String> pair = sendEmail2Kernel.getEmailContent(email, template, order);

        json.put("theme", pair.getLeft());
        json.put("emailContent", pair.getRight());
        return R.ok(json);

    }

    /**
     * 新增邮件记录
     */
    @SaCheckPermission("system:EmailList:add")
    @Log(title = "邮件记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody EmailListBo bo) {
        return toAjax(emailListService.insertByBo(bo));
    }

    /**
     * 修改邮件记录
     */
    @SaCheckPermission("system:EmailList:edit")
    @Log(title = "邮件记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody EmailListBo bo) {
        return toAjax(emailListService.updateByBo(bo));
    }

    /**
     * 删除邮件记录
     *
     * @param emailIds 主键串
     */
    @SaCheckPermission("system:EmailList:remove")
    @Log(title = "邮件记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{emailIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] emailIds) {
        return toAjax(emailListService.deleteWithValidByIds(List.of(emailIds), true));
    }

    /**
     * 删除邮件记录
     *
     * @param type 邮件类型
     */
    @SaCheckPermission("system:EmailList:remove")
    @Log(title = "邮件记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeAll/{type}")
    public R<Void> remove(@PathVariable Integer type) {
        if (type == null) {
            return R.fail("邮件类型不能为空");
        }
        int count = emailListMapper.delete(new LambdaQueryWrapper<EmailList>().eq(EmailList::getCreateId, LoginHelper.getUserId()).eq(EmailList::getType, type));
        return count > 0 ? R.ok() : R.fail("删除失败");
    }

    /**
     * 邮件失败重发
     */
    @SaCheckPermission("system:EmailList:resend")
    @Log(title = "邮件失败重发", businessType = BusinessType.OTHER)
    @PostMapping("/reSend")
    public R<?> reSend(@RequestBody EmailListBo bo) {

        // 获取当前的用户信息
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            return R.fail("未获取到用户信息");
        }

        if (!LoginHelper.isAgent()) {
            return R.fail("暂无权限操作");
        }

        bo.setStatus(4);
        bo.setType(1);
        bo.setCreateId(loginUser.getUserId());
        List<EmailList> emails = emailListService.selectList(bo);
        if(emails.isEmpty()) {
            return R.fail("未查询到失败邮件");
        }

        sendEmail2Kernel.sendFailOrderEmail(emails);

        return R.ok("提交成功，邮件将依次发送");
    }
}
